package com.ei.itop.login.controller;

import java.util.Locale;
import java.util.Map;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;

import com.ailk.dazzle.exception.BizException;
import com.ailk.dazzle.util.sec.Encrypt;
import com.ailk.dazzle.util.type.StringUtils;
import com.ei.itop.common.constants.SysConstants;
import com.ei.itop.common.dbentity.CcUser;
import com.ei.itop.common.dbentity.ScOp;
import com.ei.itop.common.dbentity.ScOrg;
import com.ei.itop.common.util.CookieUtil;
import com.ei.itop.common.util.LoginUtil;
import com.ei.itop.common.util.SessionUtil;
import com.ei.itop.login.bean.LoginInfo;
import com.ei.itop.login.service.LoginService;
import com.ei.itop.scmgnt.service.ScOrgService;

@Controller
@RequestMapping("")
public class LoginController {

	private static final Logger log = Logger.getLogger(LoginController.class);

	@Autowired
	LoginService loginService;
	
	@Autowired
	ScOrgService orgService;

	@Autowired
	CookieLocaleResolver localeResolver;

	@RequestMapping("/i18n")
	public String changeLocale(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String locale = request.getParameter("locale");
		if (locale == null || locale.equals("")) {
			return "redirect:/login.jsp";
		} else {
			Locale newLocale = org.springframework.util.StringUtils
					.parseLocaleString(locale);
			localeResolver.setLocale(request, response, newLocale);
			return "redirect:/login.jsp";
		}
	}

	@RequestMapping("/doLogin")
	public String doLogin(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		long start = System.currentTimeMillis();
		String fromURL = request.getParameter("fromURL");
		if(StringUtils.isEmpty(fromURL)){
			fromURL = "/page/incidentmgnt/main";
		}
		// 获取登录的操作员类型
		String opType = request.getParameter("opType");
		// 用户名
		String accountNo = request.getParameter("accountNo");
		// 密码
		String accountPwd = request.getParameter("accountPwd");
		// 验证码
		String verifyCode = request.getParameter("verifyCode");
		// 记住用户名密码
		String loginRemember = request.getParameter("loginRemember");
		// 校验验证码
		if (!request.getSession()
				.getAttribute(SysConstants.SessionAttribute.LOGIN_VERIFY_CODE)
				.equals(verifyCode)) {
			request.setAttribute("errorMsg", SessionUtil.getRequestContext()
					.getMessage("i18n.login.VerifyCodeError"));
			request.setAttribute("accountNo", accountNo);
			log.debug("验证码不正确");
			recordLog(start);
			return "/login";
		} else {
			// 检查信息完整性
			if (StringUtils.isEmpty(accountNo)) {
				request.setAttribute("errorMsg", SessionUtil.getRequestContext()
						.getMessage("i18n.login.AccountEmpty"));
				log.debug("用户名输入不能为空");
				recordLog(start);
				return "/login";
			}
			// 检查信息完整性
			if (StringUtils.isEmpty(accountPwd)) {
				request.setAttribute("errorMsg", SessionUtil.getRequestContext()
						.getMessage("i18n.login.PasswordEmpty"));
				log.debug("密码输入不能为空");
				recordLog(start);
				return "/login";
			}
			// 封装登录Bean
			LoginInfo li = new LoginInfo();
			li.setLoginCode(accountNo.toLowerCase());
			li.setLoginPasswd(accountPwd);
			li.setIdentifyingCode(verifyCode);
			// 如果是用户登录
			if (SysConstants.OpAttribute.OP_ROLE_USER.equals(opType)) {
				CcUser user = null;
				try {
					log.debug("开始执行Service登录操作");
					user = loginService.userLogin(li);
					log.debug("执行Service登录操作完毕");
				} catch (BizException e) {
					log.warn("", e);
					request.setAttribute("errorMsg", e.getMessage());
					request.setAttribute("accountNo", accountNo);
					log.debug("发生业务异常");
					recordLog(start);
					return "/login";
				} catch (Exception e) {
					log.error("", e);
					request.setAttribute("accountNo", accountNo);
					request.setAttribute("errorMsg", SessionUtil.getRequestContext()
							.getMessage("i18n.login.SystemError"));
					log.debug("发生系统异常");
					recordLog(start);
					return "/login";
				}
				// 账号密码不正确
				if (user == null) {
					request.setAttribute("accountNo", accountNo);
					request.setAttribute("errorMsg", SessionUtil.getRequestContext()
							.getMessage("i18n.login.AccountPasswordNotCorrect"));
					recordLog(start);
					log.debug("账号密码不正确，请重新输入");
					return "/login";
				} else {
					log.debug("正常登录，将信息放入Session");
					LoginUtil.putLoginInfo2Session(request, response, accountNo,
							user.getCcUserId(), user.getLoginCode(),
							user.getOpName(),
							user.getLastName() + "." + user.getFirstName(),
							opType, user.getScOrgId(), user.getScOrgName(),
							user.getCcCustId(), user.getOpKind(),accountPwd,loginRemember);
					log.debug("正常登录，将信息放入Session完毕，即将跳转");
					recordLog(start);
					return "redirect:"+fromURL;
				}
			}
			// 如果是服务方登录
			else if (SysConstants.OpAttribute.OP_ROLE_OP.equals(opType)) {
				ScOp op = null;
				try {
					op = loginService.adviserLogin(li);
				} catch (BizException e) {
					log.warn("", e);
					request.setAttribute("accountNo", accountNo);
					request.setAttribute("errorMsg", e.getMessage());
					recordLog(start);
					return "/login";
				} catch (Exception e) {
					log.error("", e);
					request.setAttribute("accountNo", accountNo);
					request.setAttribute("errorMsg", SessionUtil.getRequestContext()
							.getMessage("i18n.login.SystemError"));
					recordLog(start);
					return "/login";
				}
				// 账号密码不正确
				if (op == null) {
					request.setAttribute("accountNo", accountNo);
					request.setAttribute("errorMsg", SessionUtil.getRequestContext()
							.getMessage("i18n.login.AccountPasswordNotCorrect"));
					return "/login";
				} else {
					//获取组织名称
					ScOrg scOrg = orgService.queryScOrg(op.getScOrgId());
					//放入Session
					LoginUtil.putLoginInfo2Session(request, response, accountNo,
							op.getScOpId(), op.getLoginCode(), op.getOpName(),
							op.getLastName() + "." + op.getFirstName(), opType,
							op.getScOrgId(), scOrg.getScOrgName(), null, op.getOpKind().longValue(),accountPwd,loginRemember);
					recordLog(start);
					return "redirect:"+fromURL;
				}
			}
			return "/login";
		}
	}
	
	@RequestMapping("/loginByKey")
	public String doLoginByKey(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String fromURL = request.getParameter("fromURL");
		if(StringUtils.isEmpty(fromURL)){
			fromURL = "/page/incidentmgnt/main";
		}
		Cookie loginCookie = CookieUtil.getCookie(request.getCookies(), SysConstants.CookieAttribute.LOGIN_KEY);
		if(loginCookie==null||StringUtils.isEmpty(loginCookie.getValue())){
			throw new Exception("cookie中并未找到可以登录的信息");
		}
		String[] loginInfo = Encrypt.decrypt(loginCookie.getValue()).split(SysConstants.CookieAttribute.LOGIN_KEY_SEP);
		// 获取登录的操作员类型
		String opType = loginInfo[0];
		// 用户名
		String accountNo = loginInfo[1];
		// 密码
		String accountPwd = loginInfo[2];
		// 封装登录Bean
		LoginInfo li = new LoginInfo();
		li.setLoginCode(accountNo.toLowerCase());
		li.setLoginPasswd(accountPwd);
		// 如果是用户登录
		if (SysConstants.OpAttribute.OP_ROLE_USER.equals(opType)) {
			CcUser user = null;
			try {
				user = loginService.userLogin(li);
			} catch (BizException e) {
				log.warn("", e);
				request.setAttribute("errorMsg", e.getMessage());
				request.setAttribute("logByKeyError", true);
				request.setAttribute("accountNo", accountNo);
				return "/login";
			} catch (Exception e) {
				log.error("", e);
				request.setAttribute("accountNo", accountNo);
				request.setAttribute("errorMsg", SessionUtil.getRequestContext()
						.getMessage("i18n.login.SystemError"));
				request.setAttribute("logByKeyError", true);
				return "/login";
			}
			// 账号密码不正确
			if (user == null) {
				request.setAttribute("accountNo", accountNo);
				request.setAttribute("errorMsg", SessionUtil.getRequestContext()
						.getMessage("i18n.login.AccountPasswordNotCorrect"));
				request.setAttribute("logByKeyError", true);
				doLogout(request,response);
				return "/login";
			} else {
				log.debug("正常登录，将信息放入Session");
				LoginUtil.putLoginInfo2Session(request, response, accountNo,
						user.getCcUserId(), user.getLoginCode(),
						user.getOpName(),
						user.getLastName() + "." + user.getFirstName(),
						opType, user.getScOrgId(), user.getScOrgName(),
						user.getCcCustId(), user.getOpKind(),accountPwd,null);
				log.debug("正常登录，将信息放入Session完毕，即将跳转");
				return "redirect:"+fromURL;
			}
		}
		// 如果是服务方登录
		else if (SysConstants.OpAttribute.OP_ROLE_OP.equals(opType)) {
			ScOp op = null;
			try {
				op = loginService.adviserLogin(li);
			} catch (BizException e) {
				log.warn("", e);
				request.setAttribute("accountNo", accountNo);
				request.setAttribute("errorMsg", e.getMessage());
				request.setAttribute("logByKeyError", true);
				return "/login";
			} catch (Exception e) {
				log.error("", e);
				request.setAttribute("accountNo", accountNo);
				request.setAttribute("errorMsg", SessionUtil.getRequestContext()
						.getMessage("i18n.login.SystemError"));
				request.setAttribute("logByKeyError", true);
				return "/login";
			}
			// 账号密码不正确
			if (op == null) {
				request.setAttribute("accountNo", accountNo);
				request.setAttribute("errorMsg", SessionUtil.getRequestContext()
						.getMessage("i18n.login.AccountPasswordNotCorrect"));
				request.setAttribute("logByKeyError", true);
				doLogout(request,response);
				return "/login";
			} else {
				//获取组织名称
				ScOrg scOrg = orgService.queryScOrg(op.getScOrgId());
				//放入Session
				LoginUtil.putLoginInfo2Session(request, response, accountNo,
						op.getScOpId(), op.getLoginCode(), op.getOpName(),
						op.getLastName() + "." + op.getFirstName(), opType,
						op.getScOrgId(), scOrg.getScOrgName(), null, op.getOpKind().longValue(),accountPwd,null);
				return "redirect:"+fromURL;
			}
		}
		return "/login";
	}

	@RequestMapping("/login-bugfix-hb")
	public String doLoginFixBug(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// 用户名
		String accountNo = "abcuser2@163.com";
		// 密码
		String accountPwd = "sdn";
		// 封装登录Bean
		LoginInfo li = new LoginInfo();
		li.setLoginCode(accountNo.toLowerCase());
		li.setLoginPasswd(accountPwd);
		CcUser user = null;
		try {
			user = loginService.userLogin(li);
		} catch (BizException e) {
			log.warn("", e);
			request.setAttribute("errorMsg", e.getMessage());
			request.setAttribute("accountNo", accountNo);
			log.debug("发生业务异常");
			return "/login";
		} catch (Exception e) {
			log.error("", e);
			request.setAttribute("accountNo", accountNo);
			request.setAttribute("errorMsg", "登录异常：系统临时故障，请稍后再试");
			log.debug("发生系统异常");
			return "/login";
		}
		// 账号密码不正确
		if (user == null) {
			request.setAttribute("accountNo", accountNo);
			request.setAttribute("errorMsg", "账号密码不正确，请重新输入");
			return "/login";
		} else {
			LoginUtil.putLoginInfo2Session(request, response, accountNo,
					user.getCcUserId(), user.getLoginCode(), user.getOpName(),
					user.getLastName() + "." + user.getFirstName(), "USER",
					user.getScOrgId(), user.getScOrgName(), user.getCcCustId(),
					user.getOpKind(),accountPwd,"");
			return "redirect:/page/incidentmgnt/main";
		}
	}

	private void recordLog(long start) {
		long end = System.currentTimeMillis();
		log.debug("controller登录结束，耗时（ms）：" + (end - start));
	}

	@RequestMapping("/doLogout")
	public String doLogout(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		//删除当前登录的cookie
		Cookie cookie = new Cookie(SysConstants.CookieAttribute.LOGIN_KEY, null);
		cookie.setMaxAge(-1);
		response.addCookie(cookie);
		request.setAttribute("logByKeyError",true);
		//注销会话
		request.getSession().invalidate();
		return "/login";
	}
	
	
	@Resource(name = "mailSendConfig")
	Map<String, String> mailSendConfig;

	@Autowired
	JavaMailSender mailSender;
	
	@RequestMapping("/mail/test")
	@ResponseBody
	public String testMail(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		MimeMessagePreparator preparator = new MimeMessagePreparator() {
			public void prepare(MimeMessage mimeMessage)
					throws Exception {
				MimeMessageHelper message = new MimeMessageHelper(
						mimeMessage, true, "GBK");
				message.setTo("vintin.liu@eiconsulting.cn");// 设置接收方的email地址
				message.setSubject("test!");// 设置邮件主题
				message.setFrom(mailSendConfig.get("mail.from"));// 设置发送方地址
				message.setText("test", true);
			}
		};
		try {
			mailSender.send(preparator);
		} catch (Exception e) {
			log.error("", e);
			throw new BizException("测试邮件发送失败，" + e.getMessage(), e);
		}
		return "success";
	}

	

}
